<?php

namespace App\Http\Controllers\Web\Auth;

use App\Http\Controllers\Web\Controller;
use App\Repositories\SmsCodeRepository;
use Illuminate\Http\Request;

class SmsController extends Controller
{
    public function send(Request $request, SmsCodeRepository $smsCodeRepository)
    {
        $params = $request->validate([
            'phone' => 'required|string|regex:/^1[3456789]\d{9}$/',
        ], [
            'phone.required' => '请输入手机号',
            'phone.length' => '手机号长度必须为11位',
            'phone.regex' => '手机号格式错误',
        ]);

        // 限流
        $count = $smsCodeRepository->throttle('web',$params['phone']);
        if ($count >= 3) {
            abort(403, '短信验证码发送过于频繁');
        }

        $sms = $smsCodeRepository->sendShortMessage('web',$params['phone']);

        return response()->json([
            'message' => '短信验证码发送成功',
            'success' => true,
            'data' => [
                'key' => $sms->key,
                'code' => $sms->code,
            ]
        ]);
    }
}
